package design.mode.effective_java.chapter2.item3;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

/**
 *  第一种单例成员变量是一个final字段
 *
 * @author ZhongMingde on 2021/8/3
 */

public class Elvis {
    public static final Elvis INSTANCE = new Elvis();

    private Elvis() {

    }

    public void leaveTheBuilding() {
        System.out.println("=======");
    }

    // 使用反射调用私有构造函数
    public static void main(String[] args) {
        Constructor<?>[] constructors = Elvis.class.getDeclaredConstructors();
        AccessibleObject.setAccessible(constructors, true);
        Arrays.stream(constructors).forEach(name -> {
            if (name.toString().contains("Elvis")) {
                try {
                    Elvis instance = (Elvis) name.newInstance();
                    instance.leaveTheBuilding();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
